import { FC, memo, useState, useEffect } from 'react'
import { RightTopWrapper } from './style'
import LtAvatar from '@/base-ui/lt-avatar'
import LtModel from '@/base-ui/lt-modal'
import { AvatarModalWrapper } from '@/pages/home/style'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { setAvatarActions } from '@/store/module/options'

interface IState {
  children?: React.ReactNode
}

const RightTop: FC<IState> = memo(() => {
  const dispatch = useAppDispatch()

  // 关闭弹层
  const [isModel, setIsModel] = useState(false)
  const onClose = () => {
    setIsModel(false)
  }

  // 头像列表
  const { avatarList } = useAppSelector(
    (state) => ({
      avatarList: state.options.avatarList
    }),
    shallowEqualApp
  )

  // 点击头像
  const clkAvatar = () => {
    setIsModel(true)
  }

  // 显示用户头像
  const [avatar, setAvatar] = useState<string>(
    localStorage.getItem('avatar') ||
      'https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg?param=180y180'
  )

  // 选择头像
  const chooseAvatar = (e: any, url: string) => {
    setAvatar(url)
    setIsModel(false)
    localStorage.setItem('avatar', url)
    dispatch(setAvatarActions(url))
  }

  return (
    <div>
      <RightTopWrapper>
        {/* 搜索 */}
        <div className="search">
          <input type="text" placeholder="未来在等待着你的探索..." />
          <span className="iconfont icon icon-sousuo"></span>
        </div>
        {/* 用户选择的头像 */}
        <div className="avatar">
          <LtAvatar clkAvatar={clkAvatar} src={avatar} shape="square" size="40"></LtAvatar>
        </div>
      </RightTopWrapper>
      {/* 全局的弹层用于用户选择头像 */}
      <LtModel isModel={isModel} onClose={onClose}>
        <AvatarModalWrapper>
          {avatarList.map((item: string, index: number) => {
            return (
              <div className="avatar_item" key={index}>
                <LtAvatar src={item} size={64} shape="square" clkAvatar={chooseAvatar}></LtAvatar>
              </div>
            )
          })}
        </AvatarModalWrapper>
      </LtModel>
    </div>
  )
})

export default RightTop
